<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsConsultation;

class GoodsConsultationManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加商品咨询
     * @param array $data
     * @return GoodsConsultation
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsConsultation(array $data)
    {
        $goodsConsult = new GoodsConsultation();
        $goodsConsult->valuesSet($data);
        $goodsConsult->setConsultTime(time());

        $this->entityManager->persist($goodsConsult);
        $this->entityManager->flush();

        return $goodsConsult;
    }

    /**
     * 编辑回复商品咨询
     * @param array $data
     * @param GoodsConsultation $consultation
     * @return GoodsConsultation
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoodsConsultation(array $data, GoodsConsultation $consultation)
    {
        $consultation->valuesSet($data);
        $this->entityManager->flush();

        return $consultation;
    }

    /**
     * 删除商品咨询
     * @param GoodsConsultation $goodsConsultation
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoodsConsultation(GoodsConsultation $goodsConsultation)
    {
        $this->entityManager->remove($goodsConsultation);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 删除商品下的所有咨询
     * @param $goodsId
     * @return bool
     */
    public function deleteOneGoodsMoreConsult($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(GoodsConsultation::class, 'c')->where('c.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();

        return true;
    }
}